package com.cdn.auth.component.impl;

import com.cdn.auth.component.IAuth;
import com.cdn.auth.consts.CAuthConst;
import com.cdn.auth.context.UserContext;
import com.cdn.auth.user.UserDetails;
import com.cdn.auth.user.UserInfo;
import org.springframework.stereotype.Component;

/**
 * 蔡定努
 * 2024/06/13 22:31
 */
@Component(CAuthConst.DEFAULT_AUTH_BEAN)
public class CAuthComponent implements IAuth {

    /**
     * @param permission
     * @return boolean
     */
    @Override
    public boolean hasAuth(String permission) {
        try {
            UserInfo userInfo = UserContext.get();
            UserDetails userDetails = userInfo.getUserDetails();
            return userDetails.getAuthoritys().contains(permission);
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * @param permissions
     * @return boolean
     */
    @Override
    public boolean hasAnyAuth(String... permissions) {
        try {
            UserDetails userDetails = UserContext.get().getUserDetails();
            for (String permission : permissions) {
                if (userDetails.getAuthoritys().contains(permission)) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    ;

    /**
     * @param permissions
     * @return boolean
     */
    @Override
    public boolean hasAllAuth(String... permissions) {
        try {

            UserDetails userDetails = UserContext.get().getUserDetails();
            for (String permission : permissions) {
                if (!userDetails.getAuthoritys().contains(permission)) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * @param role
     * @return boolean
     */
    public boolean hasRole(String role) {
        try {

            UserDetails userDetails = UserContext.get().getUserDetails();
            return userDetails.getRoles().contains(role);
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * @param roles
     * @return boolean
     */
    public boolean hasAnyRole(String... roles) {
        try {
            UserDetails userDetails = UserContext.get().getUserDetails();
            for (String role : roles) {
                if (userDetails.getRoles().contains(role)) {
                    return true;
                }
            }
        } catch (Exception ignored) {
        }
        return false;
    }
}
